/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package coordinator;

import Config.ConfigReader;
import DatabaseManager.DatabaseManager;
import Server.EventReceiver;
import Server.ClientListener;
import iLogger.iLogger;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * EventReceiver, se encarga de autorizar a los event catchers.
 * @author Administrador
 */
public class Coordinator implements EventReceiver{

    // nuestro escuchador de clientes
    private static ClientListener listener;
    // escucha los reportes de estado de los clientes
    private static ClientListener statusListener; 
    // lista de pedidos otorgados
    private static ClientListener pingListener;
    // lista de pedidos otorgados

    private static Vector authorized = null;

    private static int authorizationPort = 3005;
    private static int reportPort = 3006;
    private static int pingPort = 3007;
            
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {        
        
        try {
            // vemos en qué puerto escucha el listener
            authorizationPort = ConfigReader.getInt("authorizationPort");
            reportPort = ConfigReader.getInt("reportPort");
            pingPort = ConfigReader.getInt("pingPort");
        } catch (Exception ex) {
           System.out.println(ex.getMessage());
        }                
        authorized = new Vector();
        
        listener = new ClientListener(authorizationPort, new Coordinator());    
        listener.start();                                        
        
        statusListener = new ClientListener(reportPort, new Coordinator());
        statusListener.start();                

        pingListener = new ClientListener(pingPort, new Coordinator());
        pingListener.start();
    }

    public void receiveMessage(String strMessage, Socket socket) {  

    	String nOrder = null;
    	int eventCatcherId = 0;
    	
        // usamos este PrintStream para responder al cliente
        PrintStream os = null;

        if(socket.getLocalPort()==authorizationPort)
        {
            String response;

            try {
                JSONObject msg = new JSONObject(strMessage);
                nOrder = msg.getString("nOrder");
                eventCatcherId = msg.getInt("EventCatcher");
            } catch (JSONException ex) {
                Logger.getLogger(Coordinator.class.getName()).log(Level.SEVERE, null, ex);
            }

            System.out.println("Authorization request for " + nOrder + " from " + eventCatcherId);

            if(!authorized.contains(nOrder)){
                response = "OK";
                authorized.add(nOrder);
            }
            else response = "NO";

            try {
                os = new PrintStream(socket.getOutputStream());
            } catch (IOException ex) {
              iLogger.log(ex.getMessage());
            }

            // respondemos al cliente
            os.println(response);
        }
        else if(socket.getLocalPort()==reportPort)
        {
               DatabaseManager connection = new DatabaseManager();
                // recibimos un mensaje de status
                // lo abrimos y sacamos la info
                try {
                    JSONObject msg = new JSONObject(strMessage);
                    int id = msg.getInt("id");
                    String state = msg.getString("state");
                    System.out.println("EventCatcher "+id+" en estado ["+state+"]");
                    connection.insertCatcherState(id, state);
                } catch (Exception ex) {
                    Logger.getLogger(Coordinator.class.getName()).log(Level.SEVERE, null, ex);
                    }
        }else if(socket.getLocalPort()==pingPort)
        {
            try {
                os = new PrintStream(socket.getOutputStream());
            } catch (IOException ex) {
              iLogger.log(ex.getMessage());
            }

            // respondemos al cliente
            os.println("PONG!");
        }

    }
}

     